package com.company.leetcode同类题型.String;

/**
 * 最长公共前缀
 * */

public class longestCommonPrefix {
    public static void main(String[] args) {
        String[] strs = new String[]{"flower","flow","flight"};
        longestCommonPrefix obj = new longestCommonPrefix();
        String s = obj.longestCommonPrefix(strs);
        System.out.println("最长公共前缀是："+s);
    }

    public String longestCommonPrefix(String[] strs) {
        int minL = 201;
        if(strs.length ==1) {
            return strs[0];
        }
        //找到所有字符串中的最小长度
        for(int i=0;i<strs.length;i++){
            minL = Math.min(strs[i].length(),minL);
        }
        if(minL == 0){
            return "";
        }
        int l=-1;
        boolean ok = true;
        while(l+1 < minL && ok){
            char ch = strs[0].charAt(l+1);
            for(int i=1;i<strs.length;i++){
                if(ch != strs[i].charAt(l+1)) {
                    ok = false;
                    l--;
                    break;
                }
            }
            l++;
        }
        return strs[0].substring(0,l+1);
    }
}
